package cn.cdeden.resource.utils;

import cn.cdeden.resource.unified.domain.OnlineConfig;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * TODO
 *
 * @author username
 * @date 2024/12/12 9:29
 * @describe:
 **/
public class FileUtil extends cn.hutool.core.io.FileUtil{
    public static String getDocumentType(String suffix) {
        String word = "txt doc docx";
        List<String> wordList = Arrays.asList(word.split(" "));
        String ppt = "ppt pps pptx";
        List<String> pptList = Arrays.asList(ppt.split(" "));
        String excel = "xlsx xls";
        List<String> excelList = Arrays.asList(excel.split(" "));
        for (String s : wordList) {
            if (suffix.equals(s)) return "word";
        }
        for (String s : pptList) {
            if (suffix.equals(s)) return "ppt";
        }
        for (String s : excelList) {
            if (suffix.equals(s)) return "excel";
        }
        return null;
    }

    /**
     * 通过OnlyOffice 将文件转换成pdf的下载流
     * @param fileUrl       文件的下载流地址
     * @param fileType      文件原始类型（后缀）
     * @param key           缓存中的key
     * @param outputType    转换为的类型（后缀）
     * @param title         转换后的文件名称
     */
    public static String convertToPdf(String fileUrl,String fileType,String key,String outputType,String title){
        OnlineConfig bean = SpringUtil.getBean(OnlineConfig.class);
        String url = bean.getOnlyOffice() + "/ConvertService.ashx";
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 添加请求头
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");

            // 构建参数
            JSONObject parameters = new JSONObject();
            parameters.put("async", false);
            parameters.put("filetype", fileType);
            parameters.put("key", key);
            parameters.put("outputtype", outputType);
            parameters.put("title", title);
            parameters.put("url", fileUrl);
            // 发送POST请求
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(parameters.toJSONString());
            wr.flush();
            wr.close();

            // 读取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            // 创建一个DocumentBuilderFactory对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            // 创建一个DocumentBuilder对象
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 使用DocumentBuilder解析XML输入流，得到一个Document对象
            org.w3c.dom.Document doc = builder.parse(new InputSource(new StringReader(response.toString())));

            // 获取根元素
            org.w3c.dom.Element root = doc.getDocumentElement();

            // 获取<FileUrl>标签
            NodeList fileUrlList = root.getElementsByTagName("FileUrl");
            Node node = fileUrlList.item(0);
            return node.getTextContent();
        }catch (Exception e) {

        }

        return null;
    }

    public static File stringToFile(String realName,String suffix,String string) {
        // 要写入的字符串
        String fileName = realName == null ? String.valueOf(System.currentTimeMillis()) : realName + "." + suffix == null ? "txt" : suffix;
        // 创建文件对象
        File file = new File(fileName);

        // 创建 BufferedWriter
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            // 写入字符串到文件
            writer.write(string);
            System.out.println("字符串成功写入到文件中: " + file.getAbsolutePath());
        } catch (IOException e) {
            System.err.println("写入文件时发生错误: " + e.getMessage());
        }
        return file;
    }
}
